package models

import (
	"database/sql"
	"time"
)

type User struct {
	ID        int64  `json:"id"`
	UserName  string `json:"user_name"`
	Password  string `json:"password"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
	DB        *sql.DB
}

// CreateUser 创建用户
func (u *User) CreateUser() error {
	// 使用预处理语句插入用户数据
	query := `INSERT INTO users (user_name, password, created_at, updated_at) VALUES (?, ?, ?, ?)`
	_, err := u.DB.Exec(query, u.UserName, u.Password, time.Now(), time.Now())
	return err
}

// GetUserByUsername 根据用户名获取用户
func GetUserByUsername(db *sql.DB, username string) (*User, error) {
	var user User
	query := `SELECT id, user_name, password, created_at, updated_at FROM users WHERE user_name = ?`
	err := db.QueryRow(query, username).Scan(&user.ID, &user.UserName, &user.Password, &user.CreatedAt, &user.UpdatedAt)
	if err != nil {
		return nil, err
	}
	user.DB = db
	return &user, nil
}
